package org.amos.filestorage.platform.s3;

import cn.hutool.core.util.StrUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import org.amos.filestorage.exception.FileStorageException;
import org.amos.filestorage.platform.AbstractFilePlatform;
import org.amos.filestorage.platform.config.s3.TencentFilePlatformConfig;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.Consumer;

/**
 * 腾讯云 COS 存储
 */
public class TencentFilePlatform extends AbstractFilePlatform<TencentFilePlatformConfig> {

    private COSClient client;

    public TencentFilePlatform(String id, TencentFilePlatformConfig config) {
        super(id, config);
    }

    @Override
    public void initClient() {
        COSCredentials cred = new BasicCOSCredentials(config.getAccessKey(), config.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(config.getRegion()));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        client = new COSClient(cred, clientConfig);
    }

    @Override
    public String upload(byte[] bytes, String path, String type) {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(bytes.length);
        metadata.setContentType(type);
        client.putObject(config.getBucket(), path, new ByteArrayInputStream(bytes), metadata);
        return StrUtil.format("{}/{}", config.getDomain(), path);
    }

    @Override
    public Boolean delete(String path) {
        client.deleteObject(config.getBucket(), path);
        return Boolean.TRUE;
    }


    @Override
    public Boolean exists(String path) {
        return client.doesObjectExist(config.getBucket(), path);
    }

    @Override
    public void download(String path, Consumer<InputStream> consumer) {
        COSObject object = client.getObject(config.getBucket(), path);
        try (InputStream in = object.getObjectContent()) {
            consumer.accept(in);
        } catch (IOException e) {
            throw new FileStorageException(org.junit.internal.Throwables.getStacktrace(e));
        }
    }
}
